<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { formSchema } from './moduleAttr.data';
  import { createModuleAttr, updateModuleAttr } from '@/api/module/module';
  import type { ModuleAttrAddReq, ModuleAttrEditReq } from '@/api/module/model/moduleModel';
  import { useMessage } from '@/hooks/web/useMessage';

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const rowId = ref<number>(0);
  const { createMessage } = useMessage();

  const getTitle = computed(() => (!unref(isUpdate) ? '新增模块属性' : '编辑模块属性'));

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      setFieldsValue({
        ...data.record,
      });
    }
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });

      // 验证extra字段的JSON格式
      if (values.extra) {
        try {
          JSON.parse(values.extra);
        } catch (e) {
          setModalProps({ confirmLoading: false });
          createMessage.error('额外配置必须是有效的JSON格式');
          return;
        }
      }

      const formData = {
        name: values.name,
        type: values.type,
        key: values.key,
        value: values.value,
        desc: values.desc,
        extra: values.extra || '',
      };

      if (unref(isUpdate)) {
        await updateModuleAttr({
          id: rowId.value,
          name: values.name,
          type: values.type,
          key: values.key,
          value: values.value,
          desc: values.desc,
          extra: values.extra || '',
        } as ModuleAttrEditReq);
      } else {
        await createModuleAttr(formData as ModuleAttrAddReq);
      }

      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
